using System;
using System.Text;

namespace PowerShellJSONParser
{
    public class JSONImpl 
    {
        public static string ConvertFromJSON(string json)
        {
            bool startStringState = false;
            bool valueState = false;
            bool arrayState = false;
            bool saveArrayState = false;

            StringBuilder sb = new StringBuilder(5000);

            foreach (char c in json.ToCharArray())
            {
                int cInt = Convert.ToInt16(c);
                if (c == '{')
                {
                    sb.Append("(New-Object PSObject ");

                    saveArrayState = arrayState;
                    valueState = false;
                    startStringState = false;
                    arrayState = false;
                }
                else if (c == '}')
                {
                    sb.Append(")");

                    arrayState = saveArrayState;
                    //startStringState = false;
                    //valueState = false;
                }
                else if (c == '"')
                {
                    //@((New-Object PSObject | Add-Member -Passthru NoteProperty "a" "b"),(New-Object PSObject "c" "d"))
                    if (startStringState == false && valueState == false && arrayState == false)
                    {
                        sb.AppendFormat("| Add-Member -Passthru NoteProperty \"");
                    }
                    else { sb.AppendFormat("\""); }

                    startStringState = true;
                }
                else if (c == ':')
                {
                    sb.Append(" ");
                    valueState = true;
                }
                else if (c == ',')
                {
                    if (arrayState)
                    {
                        sb.AppendFormat(",");
                    }
                    else
                    {
                        valueState = false;
                        startStringState = false;
                    }
                }
                else if ((cInt >= 33 && cInt <= 90) ||
                    (cInt >= 97 && cInt <= 122) ||
                    (cInt >= 48 && cInt <= 57))
                {
                    sb.Append(c);
                }

                else if (c == '[')
                {
                    sb.AppendFormat("@(");
                    arrayState = true;
                }
                else if (c == ']')
                {
                    sb.AppendFormat(")");
                    arrayState = false;
                }
                else if (c == '\t' || c == '\n' || c == '\r')
                    continue;
            }

            return sb.ToString();
        }
    }
}
